<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="系统名称">
              <el-input v-model="queryParams.name" placeholder="请输入系统名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="应用名称">
              <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="编辑中" :value="0" />
                <el-option label="已生效" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="search-buttons">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

      </el-form>
    </el-card>
    <!-- 登录要素列表 -->
    <el-card>
      <el-button type="primary" @click="handleCreate">
          <el-icon>
            <Plus />
          </el-icon>
          新增配置
        </el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange" border
        style="width: 100%" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" align="center" width="80" />
        <el-table-column prop="name" label="系统名称" align="center" />
        <el-table-column prop="appName" label="应用名称" align="center" />
        <el-table-column prop="browsers" label="浏览器支持" align="center" />
        <el-table-column prop="enabledCode" label="浏览器支持" align="center" >
          <template #default="{ row }">
            <el-tag :type="row.enabledCode === 0 ? 'info' : 'success'">{{  row.enabledCode === 0 ? '关闭' : '启用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logoUrl" label="LOGO地址" align="center">
          <template #default="{ row }">
            <el-image v-if="row.logoUrl" style="width: 50px; height: 50px" :src="row.logoUrl"
              :preview-src-list="[row.logoUrl]" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已生效' : '编辑中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="effectiveDate" label="生效日期" align="center" width="180">
          <template #default="{ row }">
            {{ formatTime(row.effectiveDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" align="center" />
        <el-table-column prop="lastUpdateTime" label="上次更新时间" align="center" width="180">
          <template #default="{ row }">
            {{ formatTime(row.lastUpdateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button type="text" @click="handleDetail(row)">详情</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #F56C6C">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery" @current-change="handleQuery" />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="登录要素详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="系统名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="应用名称">{{ detailData.appName }}</el-descriptions-item>
        <el-descriptions-item label="浏览器支持">{{ detailData.browsers }}</el-descriptions-item>
        <el-descriptions-item label="浏览器支持">
            <el-tag :type="detailData.enabledCode === 0 ? 'info' : 'success'">{{  detailData.enabledCode === 0 ? '关闭' : '启用' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="LOGO地址">
          <el-image v-if="detailData.logoUrl" style="width: 100px; height: 100px" :src="detailData.logoUrl"
            :preview-src-list="[detailData.logoUrl]" fit="cover" />
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 1 ? 'success' : 'info'">
            {{ detailData.status === 1 ? '已生效' : '编辑中' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="生效日期">{{ formatTime(detailData.effectiveDate) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detailData.updater }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(detailData.lastUpdateTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="formDialog.visible" :title="formDialog.title" width="50%" @closed="resetForm">
      <el-form ref="configForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="ID" prop="id" v-if="formDialog.isEdit">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="浏览器支持" prop="browsers">
          <el-input v-model="form.browsers" placeholder="请输入浏览器支持" />
        </el-form-item>
        <el-form-item label="布局JSON" prop="layout">
          <el-input v-model="form.layout" type="textarea" :rows="4" placeholder="请输入布局JSON" />
        </el-form-item>
        <el-form-item label="LOGO地址" prop="logoUrl">
          <el-input v-model="form.logoUrl" placeholder="请输入LOGO地址" />
          <el-upload class="upload-demo" action="/api/upload" :on-success="handleUploadSuccess" :show-file-list="false">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">编辑中</el-radio>
            <el-radio :label="1">已生效</el-radio>
          </el-radio-group>
        </el-form-item>
         <el-form-item label="验证码启用" prop="enabledCode">
          <el-radio-group v-model="form.enabledCode">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生效日期" prop="effectiveDate">
          <el-date-picker v-model="form.effectiveDate" type="datetime" placeholder="选择生效日期"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listLoginConfig,
  getLoginConfig,
  addLoginConfig,
  updateLoginConfig,
  deleteLoginConfig
} from '@/api/sysManage/loginElements.js'

// 数据状态
const loading = ref(false)
const configList = ref([])
const total = ref(0)
const configForm = ref(null)
const selectedRows = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  appName: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  appName: '',
  browsers: '',
  layout: '',
  logoUrl: '',
  status: 0,
  effectiveDate: ''
})

// 详情数据
const detailData = reactive({
  id: '',
  name: '',
  appName: '',
  browsers: '',
  layout: '',
  logoUrl: '',
  status: 0,
  effectiveDate: '',
  creator: '',
  createTime: '',
  updater: '',
  lastUpdateTime: ''
})

// 对话框状态
const detailDialog = reactive({
  visible: false
})

const formDialog = reactive({
  visible: false,
  title: '',
  isEdit: false
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection.map(item => item.enterpriseWechatConfigId)
}
// 获取配置列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listLoginConfig(queryParams)
    configList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.name = ''
  queryParams.appName = ''
  queryParams.status = ''
  getList()
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getLoginConfig(row.id)
    Object.assign(detailData, res.data)
    detailDialog.visible = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 新增配置
const handleCreate = () => {
  formDialog.visible = true
  formDialog.title = '新增登录要素'
  formDialog.isEdit = false
}

// 编辑配置
const handleEdit = async (row) => {
  try {
    const res = await getLoginConfig(row.id)
    Object.assign(form, res.data)
    formDialog.visible = true
    formDialog.title = '编辑登录要素'
    formDialog.isEdit = true
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  }
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该配置吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLoginConfig(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 上传成功处理
const handleUploadSuccess = (response) => {
  form.logoUrl = response.data.url
  ElMessage.success('上传成功')
}
// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLoginConfig(selectedRows.value.join(','))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => { })
}
// 重置表单
const resetForm = () => {
  if (configForm.value) {
    configForm.value.resetFields()
  }
  Object.assign(form, {
    id: undefined,
    name: '',
    appName: '',
    browsers: '',
    layout: '',
    logoUrl: '',
    status: 0,
    effectiveDate: ''
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await configForm.value.validate()

    if (formDialog.isEdit) {
      await updateLoginConfig(form)
      ElMessage.success('修改成功')
    } else {
      await addLoginConfig(form)
      ElMessage.success('新增成功')
    }
    formDialog.visible = false
    getList()
  } catch (error) {
    if (error && error.fields) {
      ElMessage.warning('请检查表单填写是否正确')
    } else {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.search-buttons {
  text-align: left;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.upload-demo {
  margin-top: 10px;
}
</style>